package services

import (
	"context"
	"sync"

	"github.com/beego/beego/v2/core/logs"
	"github.com/olivere/elastic/v7"
)

var (
	esClient *elastic.Client
	once     sync.Once
)

func InitElasticsearch() error {
	var err error
	once.Do(func() {
		esClient, err = elastic.NewClient(
			elastic.SetURL("http://localhost:9200"),
			elastic.SetSniff(false),
		)
		if err != nil {
			logs.Error("Failed to create Elasticsearch client:", err)
		}
	})
	return err
}

func GetClient() *elastic.Client {
	return esClient
}

func CreateProductIndex(ctx context.Context) error {
	exists, err := esClient.IndexExists("products").Do(ctx)
	if err != nil {
		return err
	}

	if !exists {
		createIndex, err := esClient.CreateIndex("products").BodyString(`
		{
			"mappings": {
				"properties": {
					"unique_code": {"type": "keyword"},
					"name": {"type": "text"},
					"price": {"type": "double"},
					"storage_time": {"type": "date"},
					"outbound_time": {"type": "date"},
					"status": {"type": "keyword"}
				}
			},
			"settings": {
				"number_of_shards": 1,
				"number_of_replicas": 0
			}
		}`).Do(ctx)
		if err != nil {
			return err
		}
		if !createIndex.Acknowledged {
			logs.Warn("Index creation not acknowledged")
		}
		logs.Info("Product index created successfully")
	}
	return nil
}
